package com.richard.library.basic.basic;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.FloatRange;
import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.StyleRes;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.LifecycleRegistry;
import androidx.lifecycle.ViewModelStore;
import androidx.lifecycle.ViewModelStoreOwner;

import com.richard.library.basic.R;
import com.richard.library.basic.basic.dict.Direction;
import com.richard.library.basic.basic.uiview.UIView;
import com.richard.library.basic.basic.uiview.UIViewImpl;
import com.richard.library.basic.eventbus.EventData;
import com.richard.library.basic.util.ActivityManager;
import com.richard.library.basic.util.DensityUtil;
import com.richard.library.basic.util.HideNavBarUtil;
import com.richard.library.basic.util.ViewUtil;
import com.richard.library.basic.widget.PlaceHolderView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * <pre>
 * Description : dialog基类
 * Author : admin-richard
 * Date : 2021/4/14 17:28
 * Changelog:
 * Version            Date            Author              Detail
 * ----------------------------------------------------------------------
 * 1.0         2021/4/14 17:28      admin-richard         new file.
 * </pre>
 */
public abstract class BasicDialog extends Dialog implements UIInitializer, LifecycleOwner, ViewModelStoreOwner {

    /*显示Dialog时是否隐藏底部导航栏按钮*/
    public static boolean isHideBottomNav;

    private LifecycleRegistry mLifecycleRegistry;
    private ViewModelStore viewModelStore;

    private PlaceHolderView mPlaceHolderView;
    private UIView mUIView;

    private float mDimAmount = 0.5f;//背景昏暗度
    private Direction direction;//dialog显示位置
    private int marginLeftRightDp = 30;//左右边距
    private int marginTopBottomDp = 30;//上下边距
    private int mAnimStyle;//进入退出动画
    private int widthDp = WindowManager.LayoutParams.WRAP_CONTENT;
    private int heightDp = WindowManager.LayoutParams.WRAP_CONTENT;
    private boolean isFirstInit = true;//是否为首次初始化
    private FragmentManager manager;


    public BasicDialog(Context context) {
        this(context, R.style.prompt_dialog_round_corner);
    }

    public BasicDialog(Context context, int themeResId) {
        super(context, themeResId);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getContext() instanceof FragmentActivity) {
            manager = ((FragmentActivity) getContext()).getSupportFragmentManager();
        } else {
            Activity activity = ActivityManager.get().current();
            if (activity instanceof FragmentActivity) {
                manager = ((FragmentActivity) activity).getSupportFragmentManager();
            }
        }

        mUIView = new UIViewImpl(getContext());
        mLifecycleRegistry = new LifecycleRegistry(this);

        this.initLayoutView();
        this.initData();
        this.bindListener();
        mLifecycleRegistry.setCurrentState(Lifecycle.State.CREATED);
    }

    @Override
    public void onAttachedToWindow() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        if (mLifecycleRegistry.getCurrentState() == Lifecycle.State.DESTROYED) {
            mLifecycleRegistry = new LifecycleRegistry(this);
            mLifecycleRegistry.setCurrentState(Lifecycle.State.CREATED);
        }

        if (isFirstInit) {
            isFirstInit = false;
            this.initParams();
        }
        super.onAttachedToWindow();
    }

    @Override
    public void onDetachedFromWindow() {
        mLifecycleRegistry.setCurrentState(Lifecycle.State.DESTROYED);
        if (viewModelStore != null) {
            viewModelStore.clear();
        }
        super.onDetachedFromWindow();
    }

    @Override
    protected void onStop() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        if (mUIView != null) {
            mUIView.dismissLoading();
            mUIView.dismissMsgDialog();
        }
        super.onStop();
    }

    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        return this.mLifecycleRegistry;
    }

    @NonNull
    @Override
    public ViewModelStore getViewModelStore() {
        if (viewModelStore == null) {
            viewModelStore = new ViewModelStore();
        }
        return viewModelStore;
    }

    @Override
    public void show() {
        if (!isHideBottomNav) {
            super.show();
            mLifecycleRegistry.setCurrentState(Lifecycle.State.RESUMED);
            return;
        }
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
        super.show();
        HideNavBarUtil.hideBottomUIMenu(getWindow());
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
        mLifecycleRegistry.setCurrentState(Lifecycle.State.RESUMED);
    }

    /**
     * 获取FragmentManager
     */
    public FragmentManager getFragmentManager() {
        return this.manager;
    }

    /**
     * 设置fragmentManger
     */
    public void setFragmentManager(FragmentManager manager) {
        this.manager = manager;
    }

    public UIView getUIView() {
        return mUIView;
    }

    /**
     * 设置视图内容占位目标view
     */
    protected void setPlaceHolderTarget(View targetView) {
        if (mPlaceHolderView != null) {
            return;
        }
        mPlaceHolderView = new PlaceHolderView(getContext(), targetView);
    }


    /**
     * 获取内容占位图
     */
    public PlaceHolderView getPlaceHolderView() {
        if (mPlaceHolderView == null) {
            throw new IllegalArgumentException("请先调用setPlaceHolderTarget()方法设置占位目标view");
        }
        return mPlaceHolderView;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EventData event) {
        this.onReceiveMessageEvent(event);
    }

    /**
     * 当接收到EventBus事件时会调用
     */
    protected void onReceiveMessageEvent(EventData event) {
    }

    /**
     * 查找布局view中的控件
     *
     * @param viewId 控件id
     */
    public <T extends View> T findViewById(@IdRes int viewId) {
        return super.findViewById(viewId);
    }

    /**
     * 初始化属性参数
     */
    private void initParams() {
        Window window = getWindow();
        if (window != null) {
            WindowManager.LayoutParams params = window.getAttributes();
            params.dimAmount = mDimAmount;

            //设置dialog显示位置
            if (direction != null) {
                switch (direction) {
                    case TOP:
                        params.gravity = Gravity.TOP;
                        break;
                    case BOTTOM:
                        params.gravity = Gravity.BOTTOM;
                        break;
                    case LEFT:
                        params.gravity = Gravity.START;
                        break;
                    case RIGHT:
                        params.gravity = Gravity.END;
                        break;
                }
            }

            //设置dialog宽度
            if (widthDp == 0) {
                params.width = ViewUtil.getScreenWidth() - 2 * DensityUtil.dp2px(marginLeftRightDp);
            } else if (widthDp == WindowManager.LayoutParams.WRAP_CONTENT
                    || widthDp == WindowManager.LayoutParams.MATCH_PARENT) {
                params.width = widthDp;
            } else {
                params.width = DensityUtil.dp2px(widthDp);
            }

            //设置dialog高度
            if (heightDp == 0) {
                params.height = ViewUtil.getScreenHeight() - 2 * DensityUtil.dp2px(marginTopBottomDp);
            } else if (heightDp == WindowManager.LayoutParams.WRAP_CONTENT
                    || heightDp == WindowManager.LayoutParams.MATCH_PARENT) {
                params.height = heightDp;
            } else {
                params.height = DensityUtil.dp2px(heightDp);
            }

            //设置dialog动画
            if (mAnimStyle != 0) {
                window.setWindowAnimations(mAnimStyle);
            }

            window.setAttributes(params);
        }
    }

    /**
     * 设置背景昏暗度
     *
     * @param level 黑色透明级别
     */
    public BasicDialog setBackgroundBlackAlphaLevel(@FloatRange(from = 0, to = 1) float level) {
        mDimAmount = level;
        return this;
    }

    /**
     * 显示方向位置
     */
    public BasicDialog setShowDirection(Direction direction) {
        this.direction = direction;
        return this;
    }

    /**
     * 设置宽高
     *
     * @param widthDp  以dp为单位的宽
     * @param heightDp 以dp为单位的高
     */
    public BasicDialog setSize(int widthDp, int heightDp) {
        this.widthDp = widthDp;
        this.heightDp = heightDp;
        return this;
    }

    /**
     * 设置宽
     *
     * @param widthDp 以dp为单位的宽
     */
    public BasicDialog setWidth(int widthDp) {
        this.widthDp = widthDp;
        return this;
    }

    /**
     * 设置高
     *
     * @param heightDp 以dp为单位的高
     */
    public BasicDialog setHeight(int heightDp) {
        this.heightDp = heightDp;
        return this;
    }

    /**
     * 设置上下margin
     *
     * @param marginLeftRightDp 左右margin
     * @param marginTopBottomDp 上下margin
     */
    public BasicDialog setMargin(int marginLeftRightDp, int marginTopBottomDp) {
        this.marginLeftRightDp = marginLeftRightDp;
        this.marginTopBottomDp = marginTopBottomDp;
        this.widthDp = 0;
        this.heightDp = 0;
        return this;
    }

    /**
     * 设置左右margin
     *
     * @param marginLeftRightDp 左右边距
     */
    public BasicDialog setMarginLeftRight(int marginLeftRightDp) {
        this.marginLeftRightDp = marginLeftRightDp;
        this.widthDp = 0;
        return this;
    }

    /**
     * 设置上下margin
     *
     * @param marginTopBottomDp 上下边距
     */
    public BasicDialog setMarginTopBottom(int marginTopBottomDp) {
        this.marginTopBottomDp = marginTopBottomDp;
        this.heightDp = 0;
        return this;
    }

    /**
     * 设置进入退出动画
     *
     * @param animStyle 动画样式id
     */
    public BasicDialog setAnimStyle(@StyleRes int animStyle) {
        mAnimStyle = animStyle;
        return this;
    }

    /**
     * 设置是否点击外部取消
     *
     * @param outCancel 点击外部是否可以关闭dialog
     */
    public BasicDialog setOutCancel(boolean outCancel) {
        super.setCancelable(outCancel);
        return this;
    }

    /**
     * 设置允许出现在其它应用上（必须先在系统设置中开启"出现在其它应用上"的权限）
     * 并且在清单文件中添加：
     * <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
     * <uses-permission android:name="android.permission.SYSTEM_OVERLAY_WINDOW" />
     */
    public BasicDialog allowCanShowOnOtherApp() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
            getWindow().setType(WindowManager.LayoutParams.TYPE_PHONE);
        } else {
            getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST);
        }
        return this;
    }
}
